
package bb.lanxing.devicelist.adapter;

import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.allen.library.helper.ShapeBuilder;
import com.allen.library.shape.ShapeTextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.databinding.DataBindingAdapters;
import bb.lanxing.databinding.LayoutItemSensorBinding;
import bb.lanxing.databinding.unit.SpeedUnit;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.databinding.utils.FormatterUtil;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.lib.devices.utils.CadenceUtils;
import bb.lanxing.lib.kt.model.CadenceData;
import bb.lanxing.lib.kt.model.HeartRateData;
import bb.lanxing.lib.kt.model.PowerRateData;
import bb.lanxing.lib.kt.model.BikeTrainerData;
import bb.lanxing.lib.kt.model.IndoorBikeData;
import bb.lanxing.lib.kt.model.CrossTrainerData;
import bb.lanxing.lib.kt.model.RowerData;
import bb.lanxing.model.database.Device;
//import bb.lanxing.util.Log;
import kotlin.collections.ArraysKt;
import kotlin.jvm.internal.Intrinsics;

public class DevicesSensorAdapter extends BaseQuickAdapter<SmartDevice, BaseDataBindingHolder<LayoutItemSensorBinding>> {
    final private static String TAG = "DevicesSensorAdapter";
    public static long MAX_CADENCE_DATA_VALIDITY = 1000;
    public static long MAX_DATA_VALIDITY = 2000;
    public static int VALUE_TYPE_SPEED = 1;
    public static int VALUE_TYPE_CADENCE = 2;
    public static int VALUE_TYPE_HEARTRATE = 3;
    public static int VALUE_TYPE_POWERRATE = 4;
    public static int VALUE_TYPE_INDOORBIKE = 5;
    public static int VALUE_TYPE_CROSSTRAINER = 6;
    public static int VALUE_TYPE_BIKETRAINER = 7;
    public static int VALUE_TYPE_ROWER = 7;
    private HashMap<String, CadenceData> cadenceDataMap;
    private HashMap<String, HeartRateData> heartRateData;
    private HashMap<String, PowerRateData> powerRateData;
    private HashMap<String, BikeTrainerData> bikeTrainerData;
    private HashMap<String, IndoorBikeData> indoorBikeData;
    private HashMap<String, CrossTrainerData> crossTrainerData;
    private HashMap<String, RowerData> rowerData;
    public DevicesSensorAdapter() {
        super(R.layout.layout_item_sensor, null);
        this.cadenceDataMap = new HashMap<>();
        this.heartRateData = new HashMap<>();
        this.powerRateData = new HashMap<>();
        this.bikeTrainerData = new HashMap<>();
        this.indoorBikeData = new HashMap<>();
        this.crossTrainerData = new HashMap<>();
        this.rowerData = new HashMap<>();
    }

    public HashMap<String, CadenceData> getCadenceDataMap() {
        return this.cadenceDataMap;
    }

    public HashMap<String, HeartRateData> getHeartRateData() {
        return this.heartRateData;
    }

    public HashMap<String, PowerRateData> getPowerRateData() {
        return this.powerRateData;
    }

    public HashMap<String, BikeTrainerData> getBikeTrainerData() {
        return this.bikeTrainerData;
    }

    public HashMap<String, IndoorBikeData> getIndoorBikeData() {
        return this.indoorBikeData;
    }

    public HashMap<String, CrossTrainerData> getCrossTrainerData() {
        return this.crossTrainerData;
    }

    public HashMap<String, RowerData> getRowerData() {
        return this.rowerData;
    }

    @Override
    public void convert(BaseDataBindingHolder<LayoutItemSensorBinding> holder, SmartDevice item) {
        ShapeBuilder shapeStrokeColor;
        LayoutItemSensorBinding binding = holder.getDataBinding();

        //update device icon in the device list
        if (binding != null) {
            DataBindingAdapters.setDeviceIcon(binding.imgSensorIcon, item.getType(), null);
            binding.tvSensorName.setText(item.getName());
        } else {
            return;
        }
        int type = item.getType();
        int flags = item.getFlags();
//        Log.d(TAG, "convert type=" + type + ", flags=" + flags + ", name=" + item.getName());

        //add patch for iGPSPORT sensors: CAD70, SPD70
        if (flags == 7) {
            if (item.getName().startsWith("SPD")) {
                item.setFlags(1);
            } else if (item.getName().startsWith("CAD")) {
                item.setFlags(2);
            }
            flags = item.getFlags();
//            Log.d(TAG, "convert updated flags =" + flags);
        }
        if (DeviceHelper.isConnected(item.getAddress())) {
            binding.tvConnected.setVisibility(View.VISIBLE);
            binding.tvNotConnect.setVisibility(View.GONE);
            binding.tvSensorData.setVisibility(View.VISIBLE);
        } else {
            binding.tvConnected.setVisibility(View.GONE);
            binding.tvNotConnect.setVisibility(View.VISIBLE);
            binding.tvSensorData.setVisibility(View.INVISIBLE);
        }
        if (type == SmartDevice.TYPE_CADENCE || type == SmartDevice.TYPE_VORTEX_CADENCE  || type == SmartDevice.TYPE_CADENCE01) {
            binding.tvCadenceMode.setVisibility(View.VISIBLE);
            if (CadenceUtils.hasWheelRevolution(flags) && CadenceUtils.hasCrankRevolution(flags)) {
                binding.tvCadenceMode.setText(R.string.device_cadence_label_wheel_and_crank);
                binding.tvCadenceMode.setTextColor(getContext().getResources().getColor(R.color.color_yellow_FFAF25));
                if (binding.tvCadenceMode.getShapeBuilder() != null) {
                    shapeStrokeColor = binding.tvCadenceMode.getShapeBuilder()
                            .setShapeStrokeColor(getContext().getResources().getColor(R.color.color_yellow_FFAF25));
                    shapeStrokeColor.into(binding.tvCadenceMode);
                }
            } else if (CadenceUtils.hasWheelRevolution(flags)) {
                binding.tvCadenceMode.setText(R.string.device_cadence_label_wheel_mode);
                binding.tvCadenceMode.setTextColor(getContext().getResources().getColor(R.color.color_yellow_FFAF25));
                if (binding.tvCadenceMode.getShapeBuilder() != null) {
                    shapeStrokeColor = binding.tvCadenceMode.getShapeBuilder()
                            .setShapeStrokeColor(getContext().getResources().getColor(R.color.color_yellow_FFAF25));
                    shapeStrokeColor.into(binding.tvCadenceMode);
                }
            } else if (CadenceUtils.hasCrankRevolution(flags)) {
                binding.tvCadenceMode.setText(R.string.device_cadence_label_crank_mode);
                binding.tvCadenceMode.setTextColor(getContext().getResources().getColor(R.color.color_11aefa));
                if (binding.tvCadenceMode.getShapeBuilder() != null) {
                    shapeStrokeColor = binding.tvCadenceMode.getShapeBuilder()
                            .setShapeStrokeColor(getContext().getResources().getColor(R.color.color_11aefa));
                    shapeStrokeColor.into(binding.tvCadenceMode);
                }
            } else {
                binding.tvCadenceMode.setVisibility(View.GONE);
            }
        } else {
            binding.tvCadenceMode.setVisibility(View.GONE);
        }

        String address = item.getAddress();
        switch (type) {
            case SmartDevice.TYPE_CADENCE, SmartDevice.TYPE_Q1, SmartDevice.TYPE_VORTEX_CADENCE, SmartDevice.TYPE_CADENCE01 -> {
                setCadenceData(binding.tvSensorData, address, flags);
            }
            case SmartDevice.TYPE_HEARTRATE, SmartDevice.TYPE_HEARTRATE_BELT, SmartDevice.TYPE_HR_X2_PRO, SmartDevice.TYPE_HEART_RATE01 -> {
                setHeartRateData(binding.tvSensorData, address);
            }
            case SmartDevice.TYPE_POWERRATE -> {
                setPowerRateData(binding.tvSensorData, address);
            }
            case SmartDevice.TYPE_BIKE_TRAINER -> {
                setBikeTrainerData(binding.tvSensorData, address);
            }
            case SmartDevice.TYPE_INDOOR_BIKE -> {
                setIndoorBikeData(binding.tvSensorData, address);
            }
            case SmartDevice.TYPE_CROSS_TRAINER -> {
                setCrossTrainerData(binding.tvSensorData, address);
            }
            case SmartDevice.TYPE_ROWER -> {
                setRowerData(binding.tvSensorData, address);
            }
            default -> {
            }
        }
    }

    public void setCadenceData(TextView textView, String address, int i) {
        if (!this.cadenceDataMap.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        CadenceData cadenceData = this.cadenceDataMap.get(address);
        if (cadenceData == null) {
            return;
        }
        if (CadenceUtils.hasWheelRevolution(i) && CadenceUtils.hasCrankRevolution(i)) {
            if (textView != null) {
                int cadence = cadenceData.getCadence();
                String cadenceDisplay = cadence + " " + UnitConstants.getCadenceUnit("m");
                textView.setText(cadenceDisplay);

//                textView.setText(cadenceData.getCadence() + ' ' + UnitConstants.getCadenceUnit("m"));
            }
            if (!CadenceUtils.hasWheelRevolution(i)) {
                return;
            }
            SpeedUnit speedUnit = new SpeedUnit(String.valueOf(cadenceData.getSpeed() * 3.6d));
            StringBuilder sb = new StringBuilder();
            sb.append((Object) (textView != null ? textView.getText() : null));
            sb.append("   ");
            sb.append(FormatterUtil.getNormalFormatSpeed(speedUnit.getValueBy("m")));
            sb.append(' ');
            sb.append(speedUnit.getUnitString("m"));
            String sb2 = sb.toString();
            if (textView != null) {
                textView.setText(sb2);
            }
        } else if (CadenceUtils.hasWheelRevolution(i)) {
            SpeedUnit speedUnit2 = new SpeedUnit(String.valueOf(cadenceData.getSpeed() * 3.6d));
            if (textView != null) {
                String speed = FormatterUtil.getNormalFormatSpeed(speedUnit2.getValueBy("m"));
                String speedDisplay = speed + " " + speedUnit2.getUnitString("m");
                textView.setText(speedDisplay);
//                textView.setText(FormatterUtil.getNormalFormatSpeed(speedUnit2.getValueBy("m")) + ' ' + speedUnit2.getUnitString("m"));
            }
        } else if (CadenceUtils.hasCrankRevolution(i) && textView != null) {
            int cadence = cadenceData.getCadence();
            String cadenceDisplay = cadence + " " + UnitConstants.getCadenceUnit("m");
            textView.setText(cadenceDisplay);
//            textView.setText(cadenceData.getCadence() + ' ' + UnitConstants.getCadenceUnit("m"));
        }
    }

    public void setHeartRateData(TextView textView, String address) {
        if (!this.heartRateData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        HeartRateData heartRateData = this.heartRateData.get(address);
        if (heartRateData == null) {
            return;
        }
        if (System.currentTimeMillis() - heartRateData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = heartRateData.getHeartRate();
            String rateDisplay = rate + " " + UnitConstants.getHeartRateUnit("m");
            textView.setText(rateDisplay);
        }
    }


    public void setPowerRateData(TextView textView, String address) {
        if (!this.powerRateData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        PowerRateData powerRateData = this.powerRateData.get(address);
        if (powerRateData == null) {
            return;
        }
        if (System.currentTimeMillis() - powerRateData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = powerRateData.getPowerRate();
            String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
            textView.setText(rateDisplay);
        }
    }

    public void setBikeTrainerData(TextView textView, String address) {
        if (!this.bikeTrainerData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
       BikeTrainerData bikeTrainerData = this.bikeTrainerData.get(address);
        if (bikeTrainerData == null) {
            return;
        }
        if (System.currentTimeMillis() - bikeTrainerData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = bikeTrainerData.getBikeTrainer();
            String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
            textView.setText(rateDisplay);
        }
    }
    public void setIndoorBikeData(TextView textView, String address) {
        if (!this.indoorBikeData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        IndoorBikeData indoorBikeData = this.indoorBikeData.get(address);
        if (indoorBikeData == null) {
            return;
        }
        if (System.currentTimeMillis() - indoorBikeData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = indoorBikeData.getIndoorBike();
            String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
            textView.setText(rateDisplay);
        }
    }

    public void setCrossTrainerData(TextView textView, String address) {
        if (!this.crossTrainerData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        CrossTrainerData crossTrainerData = this.crossTrainerData.get(address);
        if (crossTrainerData == null) {
            return;
        }
        if (System.currentTimeMillis() - crossTrainerData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = crossTrainerData.getCrossTrainer();
            String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
            textView.setText(rateDisplay);
        }
    }

    public void setRowerData(TextView textView, String address) {
        if (!this.rowerData.containsKey(address)) {
            if (textView == null) {
                return;
            }
            textView.setText("");
            return;
        }
        RowerData rowerData = this.rowerData.get(address);
        if (rowerData == null) {
            return;
        }
        if (System.currentTimeMillis() - rowerData.getTimestamp() >= MAX_DATA_VALIDITY) {
            if (textView == null) {
                return;
            }
            textView.setText("");
        } else if (textView != null) {
            int rate = rowerData.getRower();
            String rateDisplay = rate + " " + UnitConstants.getPowerRateUnit("m");
            textView.setText(rateDisplay);
        }
    }


	private int getItemPosition(String str) {
        for (SmartDevice smartDevice : getData()) {
            if (Intrinsics.areEqual(smartDevice.getAddress(), str)) {
                return getItemPosition(smartDevice);
            }
        }
        return -1;
    }

    private List<Integer> getItemPositionByType(int i) {
        ArrayList arrayList = new ArrayList();
        for (SmartDevice smartDevice : getData()) {
            if (smartDevice.getType() == i) {
                arrayList.add(getItemPosition(/*(DevicesSensorAdapter)*/ smartDevice));
            }
        }
        return arrayList;
    }

    public void updateValue(int i, CadenceData cadenceData, int i2) {
        List<Integer> list;
        if (i2 == VALUE_TYPE_CADENCE) {
            list = getItemPositionByType(SmartDevice.TYPE_CADENCE);
            list.addAll(getItemPositionByType(SmartDevice.TYPE_VORTEX_CADENCE));
            list.addAll(getItemPositionByType(SmartDevice.TYPE_Q1));
            list.addAll(getItemPositionByType(SmartDevice.TYPE_CADENCE01));
        } else {
            list = null;
        }
        if (i2 == VALUE_TYPE_HEARTRATE) {
            list = getItemPositionByType(SmartDevice.TYPE_HEARTRATE_BELT);
            list.addAll(getItemPositionByType(SmartDevice.TYPE_HEARTRATE));
            list.addAll(getItemPositionByType(SmartDevice.TYPE_HR_X2_PRO));
            list.addAll(getItemPositionByType(SmartDevice.TYPE_HEART_RATE01));
        }
        List<Integer> list2 = list;
        if (list2 != null && !list2.isEmpty()) {
            for (Integer num : list) {
                int intValue = num;
                int[] typeCadenceAndSpeedTypes = Device.getTypeCadenceAndSpeedTypes();
                int[] typeHeartRateTypes = Device.getTypeHeartRateTypes();
                int[] typeIndoorBikeTypes = Device.getTypeIndoorBikeTypes();
                if (ArraysKt.contains(typeCadenceAndSpeedTypes, i2)) {
                    this.cadenceDataMap.put(getData().get(intValue).getAddress(), cadenceData);
                    notifyItemChanged(intValue);
                } else if (ArraysKt.contains(typeHeartRateTypes, i2)) {
                        HeartRateData heartRateData = new HeartRateData(System.currentTimeMillis());
                        heartRateData.setHeartRate(i);
                        this.heartRateData.put(getData().get(intValue).getAddress(), heartRateData);
                        notifyItemChanged(intValue);
                 }
            }
        }
    }
}
